package com.wt.struggle.goodbye.sq.adapter

import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.MediaPlayer
import android.os.Bundle
import android.os.Handler
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.info.NewsInfo
import com.wt.struggle.goodbye.info.ProUserInfo
import com.wt.struggle.goodbye.user.activity.LoginActivity
import com.wt.struggle.goodbye.user.activity.ShowImageActivity
import com.wt.struggle.goodbye.user.activity.UserInfoActivity
import com.xin.lv.yang.utils.utils.DataUtil
import com.xin.lv.yang.utils.utils.ImageUtil
import kotlinx.android.synthetic.main.pick_user_item.view.*
import android.text.Layout
import android.text.StaticLayout
import android.widget.TextView
import com.wt.struggle.goodbye.base.*
import com.xin.lv.yang.utils.utils.StatusBarUtil

/**
 * 帖子信息显示adapter
 */
class PickUserAdapter(context: Context, list: ArrayList<NewsInfo>) : ProBaseAdapter<NewsInfo>(context, list) {

    /**
     *  1 为详情页面   2 为从我的收藏进入   3 为我的转载进入   4 我关注的帖子列表    5 我的回收站进入
     */
    var isEnterCode: Int = 1

    override fun onCreateView(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view = inflater.inflate(R.layout.pick_user_item, parent, false)
        return VH(view)

    }

    override fun onUpdateHolder(holder: RecyclerView.ViewHolder, position: Int, payloads: MutableList<Any>) {

        val bundle = payloads[0] as Bundle
        val set = bundle.keySet()
        val vh = holder as VH
        for (temp in set) {
            when (temp) {

                "attention" -> {

                    val info = bundle.getParcelable(temp) as ProUserInfo

                    if (info.isCollection == 1) {
                        vh.tvFocusOn.setBackgroundResource(R.drawable.gray_solid)
                        vh.tvFocusOn.setTextColor(context.resources.getColor(R.color.gray))
                        vh.tvFocusOn.text = "已关注"

                    } else {
                        vh.tvFocusOn.setBackgroundResource(R.drawable.red_kuang_line)
                        vh.tvFocusOn.setTextColor(context.resources.getColor(R.color.red))
                        vh.tvFocusOn.text = "+关注"
                    }

                }


                "isCollect" -> {
                    val isCollInfo = bundle.getParcelable<NewsInfo>("isCollect")

                    vh.tvTextCollect.text = isCollInfo.collectionCount.toString()

                    if (isCollInfo.isCollection == 1) {
                        vh.imageCollect.setImageBitmap(
                            BitmapFactory.decodeResource(
                                context.resources,
                                R.drawable.coll_y
                            )
                        )
                        vh.tvTextCollect.setTextColor(context.resources.getColor(R.color.red))

                    } else {
                        vh.imageCollect.setImageBitmap(
                            BitmapFactory.decodeResource(
                                context.resources,
                                R.drawable.coll_n
                            )
                        )
                        vh.tvTextCollect.setTextColor(context.resources.getColor(R.color.black777))
                    }

                }

                "isLike" -> {
                    val info = bundle.getParcelable<NewsInfo>("isLike")

                    vh.tvZanNumber.text = info.likeCount.toString()

                    if (info.isLike == 1) {

                        vh.imageViewZan.setImageBitmap(
                            BitmapFactory.decodeResource(
                                context.resources,
                                R.drawable.zan_y
                            )
                        )
                        vh.tvZanNumber.setTextColor(context.resources.getColor(R.color.red))

                    } else {
                        vh.imageViewZan.setImageBitmap(
                            BitmapFactory.decodeResource(
                                context.resources,
                                R.drawable.zan_n
                            )
                        )
                        vh.tvZanNumber.setTextColor(context.resources.getColor(R.color.black777))
                    }

                }

                "comment" -> {
                    val commentNum = bundle.getInt(temp)
                    vh.tvCommentNum.text = commentNum.toString()
                }

            }
        }

    }


    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val vh = holder as VH
        val info = list[position]

        show(vh, info)
    }


    /**
     * 显示数据
     */
    fun show(vh: VH, info: NewsInfo) {

        when {
            info.videoList != null && info.videoList!!.size != 0 -> {
                showVideo(vh, info)
            }

            info.audioList != null && info.audioList!!.size != 0 -> {
                showVoice(vh, info)
            }

            info.picList != null && info.picList!!.size != 0 -> {
                showPic(vh, info)
            }

            info.picsUrlList != null && info.picsUrlList!!.size != 0 -> {
                showPic(vh, info)
            }

        }


        vh.tvContentMs.setTextColor(context.resources.getColor(R.color.black))

        vh.tvContentName.text = info.circleName
        vh.tvContentMs.text = DataUtil.getEmoji(context, info.content)
        vh.tvTextCollect.text = info.collectionCount.toString()
        vh.tvZanNumber.text = info.likeCount.toString()

        //// 私信数量
        vh.tvDownZanNum.text = info.viewsCount.toString()

        vh.tvCommentNum.text = info.commentCount.toString()

        vh.tvContentMs.post {

            val lineCount = measureTextViewHeight(vh.tvContentMs, info.content!!, 0, 2)

            Log.i("result", "line------$lineCount")

            if (lineCount > 2) {
                vh.tvWatchMore.visibility = View.VISIBLE
            } else {
                vh.tvWatchMore.visibility = View.GONE
            }
        }

        val ll = info.location
        vh.linearIndex.visibility = View.VISIBLE

        val dis = info.distance

        when {

            dis != "" && dis != "0.0" -> {
                when {
                    dis.toFloat() > 1 -> vh.tvUserAddress.text = "${dis.toInt()}km"
                    dis.toFloat() < 1 -> vh.tvUserAddress.text = "<1km"
                    else -> vh.tvUserAddress.text = ""
                }
            }

            ll != null && ll != "" && ll != "null" -> {
                if (ll.contains("|")) {
                    val aa = ll.split("|")
                    vh.tvUserAddress.text = aa[0]

                } else {
                    vh.tvUserAddress.text = ll
                }
            }

            else -> {
                vh.tvUserAddress.text = "暂无地址"
            }
        }


        val userInfo = info.userExtraInfo

        if (userInfo != null) {
            ImageUtil.getInstance()
                .loadCircleImage(
                    context,
                    vh.sendImageUserHead,
                    Config.GET_IMAGE_URL + userInfo.avatar,
                    R.mipmap.logo_small
                )

            vh.tvUserName.text = userInfo.nickName

        }

        when (isEnterCode) {
            1 -> {

            }
            2 -> vh.tvFocusOn.visibility = View.GONE
            3 -> {
                vh.imageIndexTi.visibility = View.GONE
                vh.tvFocusOn.visibility = View.VISIBLE
                val time = System.currentTimeMillis()
                val createTime = info.createTime
                val indexTime = time - createTime!!

                val ti = when {
                    indexTime > 6 * 60 * 60 * 1000 -> DataUtil.longToTime(createTime / 1000, "yyyy-MM-dd")
                    indexTime > 60 * 60 * 1000 && 6 * 60 * 60 * 1000 > indexTime -> "一小时以前"
                    time - createTime < 60 * 1000 -> "一分钟内"
                    else -> ""
                }
                vh.tvUserAddress.text = ti
            }
            4 -> {
                vh.tvFocusOn.visibility = View.GONE
                vh.imgMoreFocus.visibility = View.VISIBLE
            }
            5 -> {
                vh.tvFocusOn.visibility = View.GONE
                vh.imgMoreFocus.visibility = View.GONE
            }

            else -> {

            }
        }

        showChoose(vh, info)

        showComment(vh, info)

        click(vh, info)

    }

    /**
     * 显示音频
     */
    private fun showVoice(vh: PickUserAdapter.VH, info: NewsInfo) {
        val voiceList = info.audioList

        if (voiceList != null && voiceList.size != 0) {

            val voiceInfo = voiceList[0]

            vh.layoutImageRecyclerView.visibility = View.GONE
            vh.videoParentFrame.visibility = View.GONE

            vh.voiceLinearLayout.visibility = View.VISIBLE

            val path = voiceInfo.path

            val voice = voiceInfo.domainname + if (path.startsWith("/")) {
                path.substring(1, path.length)
            } else {
                path
            }

            Log.i("result", "result------$voice")

            val mediaPlayer = MediaPlayer()
            mediaPlayer.setDataSource(voice)
            mediaPlayer.prepareAsync()

            mediaPlayer.setOnPreparedListener {

                val dd = mediaPlayer.duration / 1000

                Log.i("result", "ddd------$dd")

                val scanW = getW(context)
                val w = scanW * dd / 60

                Log.i("result", "result------" + w)

                vh.tvVoiceLen.text = "${dd}s"

                val www = if (w > scanW * 1 / 3) {
                    w
                } else {
                    w + context.resources.getDimension(R.dimen.dp_40).toInt()
                }

                vh.voiceLinearLayout.layoutParams =
                    FrameLayout.LayoutParams(
                        www,
                        FrameLayout.LayoutParams.WRAP_CONTENT
                    )
            }


            mediaPlayer.setOnCompletionListener {
                vh.imageVoice.setImageBitmap(BitmapFactory.decodeResource(context.resources, R.drawable.play_voice))

            }


            vh.voiceLinearLayout.setOnClickListener {
                ///  播放音频
                ImageUtil.getInstance().loadImageGif(context, vh.imageVoice, R.drawable.play_voice_gif)
                mediaPlayer.start()

            }
        }
    }

    /**
     * 设置的标识符 用户视频播放
     */
    var TAG = "tag"


    /**
     * 显示视频
     */
    private fun showVideo(vh: PickUserAdapter.VH, info: NewsInfo) {

        vh.layoutImageRecyclerView.visibility = View.GONE
        vh.voiceLinearLayout.visibility = View.GONE
        vh.videoParentFrame.visibility = View.VISIBLE

        val videoList = info.videoList
        val videoInfo = videoList!![0]

        val path = videoInfo.domainname + videoInfo.path.subSequence(1, videoInfo.path.length)

        Log.i("result", "加载的视频信息-------$path")

        vh.standardGSYVideoPlayer.onBackFullscreen()

        val imageView = ImageView(context)
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP

        ImageUtil.getInstance().loadVideoScreenshot(context, path, imageView, 0, null)

        vh.standardGSYVideoPlayer.thumbImageView = imageView

        vh.standardGSYVideoPlayer.setUpLazy(path, true, null, null, "视频")
        vh.standardGSYVideoPlayer.titleTextView.visibility = View.GONE
        vh.standardGSYVideoPlayer.backButton.visibility = View.GONE

        /// 设置全屏按键功能
        vh.standardGSYVideoPlayer.fullscreenButton.setOnClickListener {
            vh.standardGSYVideoPlayer.startWindowFullscreen(
                context,
                false,
                true
            )
        }

        // 防止错位设置
        vh.standardGSYVideoPlayer.playTag = TAG

        vh.standardGSYVideoPlayer.playPosition = vh.adapterPosition
        //是否根据视频尺寸，自动选择竖屏全屏或者横屏全屏
        vh.standardGSYVideoPlayer.isAutoFullWithSize = true
        //音频焦点冲突时是否释放
        vh.standardGSYVideoPlayer.isReleaseWhenLossAudio = true
        //全屏动画
        vh.standardGSYVideoPlayer.isShowFullAnimation = true
        //小屏时不触摸滑动
        vh.standardGSYVideoPlayer.setIsTouchWiget(false)

        /// 设置状态栏主题样式
        Handler().postDelayed({
            StatusBarUtil.setStatusBarLightMode((context as ProActivity).window, true)
        }, 300)

    }

    /**
     * 显示评论信息
     */
    private fun showComment(vh: PickUserAdapter.VH, info: NewsInfo) {
        /// 帖子的评论信息
        val commentView = inflater.inflate(R.layout.comment_item, null)
        vh.commentLinear.addView(commentView)

    }

    /**
     * 显示图片
     */
    private fun showPic(vh: PickUserAdapter.VH, info: NewsInfo) {
        vh.layoutImageRecyclerView.visibility = View.VISIBLE
        vh.videoParentFrame.visibility = View.GONE
        vh.voiceLinearLayout.visibility = View.GONE

        val picListArr = info.picList

        vh.layoutImageRecyclerView.isNestedScrollingEnabled = false

        if (picListArr != null && picListArr.size != 0) {

            val len = picListArr.size

            if (len != 0) {
                val codeLen = when (len) {
                    1 -> 1
                    2 -> 2
                    else -> 3
                }

                val manager = object : GridLayoutManager(context, codeLen) {

                    override fun canScrollVertically(): Boolean {
                        return false
                    }
                }

                vh.layoutImageRecyclerView.layoutManager = manager

                val picAdapter = ContentImageAdapter(context, picListArr, len, isEnterCode)

                vh.layoutImageRecyclerView.adapter = picAdapter

                picAdapter.itemClickListener = object : ItemClickListener {

                    override fun onItemClick(position: Int) {

                        val strArr = arrayListOf<String>()
                        for (temp in picListArr) {
                            strArr.add(temp.domainname + temp.path.subSequence(1, temp.path.length))
                        }

                        val intent = Intent(context, ShowImageActivity::class.java)
                        intent.putStringArrayListExtra("arr", strArr)
                        context.startActivity(intent)
                    }

                    override fun onLongClick(position: Int) {
                    }

                }

            }

        }
    }


    /**
     * 点击事件
     */
    private fun click(vh: PickUserAdapter.VH, info: NewsInfo) {

        vh.tvWatchMore.setOnClickListener {

            val text = vh.tvWatchMore.text

            if (text == "展开") {

                Log.i("result", "执行展开------")
                vh.tvContentMs.setSingleLine(false)
                vh.tvContentMs.ellipsize = null
                vh.tvWatchMore.text = "关闭"

            } else if (text == "关闭") {

                Log.i("result", "执行关闭------")
                vh.tvContentMs.maxLines = 2
                vh.tvContentMs.ellipsize = TextUtils.TruncateAt.END
                vh.tvWatchMore.text = "展开"

            }

        }

        vh.tvFocusOn.setOnClickListener {

            if (Share.getToken(context) != "") {

                val parentInfo = list[vh.adapterPosition]

                /// 发布者不为自己
                if (parentInfo.userExtraInfo!!.appUserId!!.toInt() != Share.getId(context)) {

                    if (onFocusOnClickListener != null) {
                        onFocusOnClickListener!!.onFocusOn(vh.adapterPosition)
                    }
                } else {
                    Toast.makeText(context, "自己不能关注自己！！", Toast.LENGTH_SHORT).show()
                }


            } else {
                Toast.makeText(context, "请登录", Toast.LENGTH_LONG).show()
                context.startActivity(Intent(context, LoginActivity::class.java))
            }

        }

        vh.sendImageUserHead.setOnClickListener {

            if (Share.getToken(context) != "") {

                val intent = Intent(context, UserInfoActivity::class.java)
                intent.putExtra("user", info.userExtraInfo)
                context.startActivity(intent)

            } else {
                context.startActivity(Intent(context, LoginActivity::class.java))
                Toast.makeText(context, "请登录", Toast.LENGTH_LONG).show()
            }
        }

        vh.imageCollect.setOnClickListener {
            ///  收藏
            if (Share.getToken(context) != "") {

                if (onFocusOnClickListener != null) {
                    onFocusOnClickListener!!.onCollect(vh.adapterPosition)
                }

            } else {
                context.startActivity(Intent(context, LoginActivity::class.java))
                Toast.makeText(context, "请登录", Toast.LENGTH_LONG).show()
            }

        }
        vh.imageViewZan.setOnClickListener {
            if (Share.getToken(context) != "") {

                if (onFocusOnClickListener != null) {
                    onFocusOnClickListener!!.onZan(vh.adapterPosition)
                }
            } else {
                context.startActivity(Intent(context, LoginActivity::class.java))
                Toast.makeText(context, "请登录", Toast.LENGTH_LONG).show()
            }

        }

        vh.imageViewDown.setOnClickListener {

            //// 发布私信
            if (Share.getToken(context) != "") {

                val parentInfo = list[vh.adapterPosition]

                 /// 发布者不为自己才可以发送私信
                if (parentInfo.userExtraInfo!!.appUserId!!.toInt() != Share.getId(context)) {

                    if (onFocusOnClickListener != null) {
                        onFocusOnClickListener!!.onDownZan(vh.adapterPosition)
                    }

                } else {
                    Toast.makeText(context, "自己不能给自己发私信！！", Toast.LENGTH_LONG).show()
                }

            } else {
                context.startActivity(Intent(context, LoginActivity::class.java))
                Toast.makeText(context, "请登录", Toast.LENGTH_LONG).show()
            }

        }

        vh.imageViewComment.setOnClickListener {

            if (Share.getToken(context) != "") {

                val parentInfo = list[vh.adapterPosition]
                if (parentInfo.userExtraInfo!!.appUserId!!.toInt() != Share.getId(context)) {

                    if (onFocusOnClickListener != null) {
                        onFocusOnClickListener!!.onComment(vh.adapterPosition)
                    }
                } else {
                    Toast.makeText(context, "您不能对自己做评论！！", Toast.LENGTH_SHORT).show()
                }


            } else {
                context.startActivity(Intent(context, LoginActivity::class.java))
                Toast.makeText(context, "请登录", Toast.LENGTH_LONG).show()
            }

        }

        vh.imgMoreFocus.setOnClickListener {

            if (Share.getToken(context) != "") {

                if (onFocusOnClickListener != null) {
                    onFocusOnClickListener!!.onMore(vh.adapterPosition)
                }

            } else {
                context.startActivity(Intent(context, LoginActivity::class.java))
                Toast.makeText(context, "请登录", Toast.LENGTH_LONG).show()
            }

        }

    }


    private fun showChoose(vh: VH, info: NewsInfo) {

        if (isEnterCode == 2) {

            vh.tvFocusOn.text = "已关注"
            vh.tvFocusOn.setBackgroundResource(R.drawable.gray_solid)
            vh.tvFocusOn.setTextColor(context.resources.getColor(R.color.black777))

        } else {

            if (info.userExtraInfo != null) {

                if (info.userExtraInfo!!.isCollection == 1) {
                    vh.tvFocusOn.setBackgroundResource(R.drawable.gray_solid)
                    vh.tvFocusOn.setTextColor(context.resources.getColor(R.color.gray))
                    vh.tvFocusOn.text = "已关注"

                } else {
                    vh.tvFocusOn.setBackgroundResource(R.drawable.red_kuang_line)
                    vh.tvFocusOn.setTextColor(context.resources.getColor(R.color.red))
                    vh.tvFocusOn.text = "+关注"
                }

            }
        }


        if (info.isCollection == 1) {

            vh.imageCollect.setImageBitmap(BitmapFactory.decodeResource(context.resources, R.drawable.coll_y))
            vh.tvTextCollect.setTextColor(context.resources.getColor(R.color.red))

        } else {
            vh.imageCollect.setImageBitmap(BitmapFactory.decodeResource(context.resources, R.drawable.coll_n))
            vh.tvTextCollect.setTextColor(context.resources.getColor(R.color.black777))
        }


        if (info.isLike == 1) {

            vh.imageViewZan.setImageBitmap(BitmapFactory.decodeResource(context.resources, R.drawable.zan_y))
            vh.tvZanNumber.setTextColor(context.resources.getColor(R.color.red))

        } else {
            vh.imageViewZan.setImageBitmap(BitmapFactory.decodeResource(context.resources, R.drawable.zan_n))
            vh.tvZanNumber.setTextColor(context.resources.getColor(R.color.black777))
        }

//
//        if (info.isDownZan) {
//            vh.imageViewDown.setImageBitmap(BitmapFactory.decodeResource(context.resources, R.drawable.down_zan_y))
//            vh.tvDownZanNum.setTextColor(context.resources.getColor(R.color.red))
//        } else {
//            vh.imageViewDown.setImageBitmap(BitmapFactory.decodeResource(context.resources, R.drawable.down_zan_n))
//            vh.tvDownZanNum.setTextColor(context.resources.getColor(R.color.black777))
//        }
//

    }


    /**
     * 改变状态
     */
    fun change(clickIndexPosition: Int, code: Int) {
        val info = list[clickIndexPosition]
        when (code) {
            1 -> {
                if (info.isCollection == 0) {
                    info.collectionCount++
                    info.isCollection = 1
                } else {
                    if (info.collectionCount != 0) {
                        info.collectionCount--
                        info.isCollection = 0
                    }
                }

            }

            2 -> {
                if (info.isLike == 0) {
                    info.likeCount++
                    info.isLike = 1
                } else {
                    if (info.likeCount != 0) {
                        info.likeCount--
                        info.isLike = 0
                    }
                }
            }

            3 -> {
                info.isDownZan = true
            }

            4 -> {
                info.numberOfCommented = info.numberOfCommented!! + 1
            }

            5 -> {
                if (info.status == 1) {
                    info.status = 0
                } else {
                    info.status = 1
                }
            }

            /// 关注
            6 -> {

                Log.i("result", "执行到关注------")

                val userInfo = info.userExtraInfo
                if (userInfo!!.isCollection == 0) {
                    userInfo.isCollection = 1
                } else {
                    userInfo.isCollection = 0
                }
            }
        }

        notifyItemChanged(clickIndexPosition)

    }


    inner class VH(view: View) : RecyclerView.ViewHolder(view) {
        val commentLinear = view.commentLinear
        val tvFocusOn = view.tvFocusOn
        val sendImageUserHead = view.sendImageUserHead
        val tvUserName = view.tvUserName
        val tvUserAddress = view.tvUserAddress
        val layoutImageRecyclerView = view.layoutImageRecyclerView
        val tvContentName = view.tvContentName
        val tvContentMs = view.tvContentMs
        val imageCollect = view.imageCollect
        val tvTextCollect = view.tvTextCollect
        val imageViewZan = view.imageViewZan
        val tvZanNumber = view.tvZanNumber
        val imageViewDown = view.imageViewDown
        val tvDownZanNum = view.tvDownZanNum
        val imageViewComment = view.imageViewComment
        val tvCommentNum = view.tvCommentNum
        val imgMoreFocus = view.imgMoreFocus
        val linearIndex = view.linearIndex
        val imageIndexTi = view.imageIndexTi
        val videoParentFrame = view.videoParentFrame
        val imageVoice = view.imageVoice
        val voiceLinearLayout = view.voiceLinearLayout
        val standardGSYVideoPlayer = view.standardGSYVideoPlayer
        val tvWatchMore = view.tvWatchMore
        val tvVoiceLen = view.tvVoiceLen

    }

    var onFocusOnClickListener: OnFocusOnClickListener? = null


    interface OnFocusOnClickListener {
        fun onFocusOn(position: Int)
        fun onCollect(position: Int)
        fun onZan(position: Int)
        fun onDownZan(position: Int)
        fun onComment(position: Int)
        fun onMore(position: Int)
    }

    fun getLastCharIndexForLimitTextView(textView: TextView, content: String, width: Int, maxLine: Int): Int {
        val textPaint = textView.paint
        val staticLayout = StaticLayout(content, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1f, 0f, false)
        return if (staticLayout.lineCount > maxLine) {
            staticLayout.getLineStart(maxLine) - 1
        } else {
            -1
        }
    }


    /**
     * 在不绘制textView的情况下算出textView的高度，并且根据最大行数得到应该显示最后一个字符的下标，
     * 请在主线程顺序执行，第一个返回值是最后一个字符的下标，第二个返回值是TextView最终应该占用的高度
     */
    fun measureTextViewHeight(textView: TextView, content: String, width: Int, maxLine: Int): Int {

        val textPaint = textView.paint
        val staticLayout = StaticLayout(content, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1f, 0f, false)

        var result = 0

        Log.i("result", "-------" + staticLayout.lineCount)

        if (staticLayout.lineCount > maxLine) {

            val lastIndex = staticLayout.getLineStart(maxLine) - 1

            result = StaticLayout(
                content.substring(0, lastIndex),
                textPaint,
                width,
                Layout.Alignment.ALIGN_NORMAL,
                1f,
                0f,
                false
            ).height

            return result

        } else {

            result = staticLayout.height
            return result
        }

    }


}